<?php

namespace app\api\controller\v46;

use app\aliyun\controller\AliyunFilterWord;
use app\aliyun\controller\AliyunPhone;
use app\aliyun\controller\AliyunRtc;
use app\api\controller\v2\Auth;
use app\astrologer\lib\AstrPush;
use app\chat\LiveMessage;
use app\common\cachemodel\OrdersLib;
use app\common\cachemodel\Recode;
use app\common\cachemodel\UserCoupon;
use app\common\cachemodel\ZhunleUserAccount;
use app\common\cachemodel\ZhunleUserAccountRecord;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAccount;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAccountReport;
use app\common\cachemodel\zlcr3\Zlcr3Follow;
use app\common\cachemodel\ZlcrAstr;
use app\common\lib\Util;
use app\zyhsapi\model\ZyhsAppFeedback;
use app\zyhsapi\model\ZyhsConfig;
use app\zyhsapi\model\ZyhsConsultAstrData;
use app\zyhsapi\model\ZyhsConsultChatInterceptRecord;
use app\zyhsapi\model\ZyhsConsultChatRecord;
use app\zyhsapi\model\ZyhsConsultChatRecordAstr;
use app\zyhsapi\model\ZyhsConsultChatRecordDetails;
use app\zyhsapi\model\ZyhsConsultChatRtcRecord;
use app\zyhsapi\model\ZyhsConsultChatRtcRecordComment;
use app\zyhsapi\model\ZyhsConsultQuestion;
use app\zyhsapi\model\ZyhsConsultRtcUserBenefits;
use app\zyhsapi\model\ZyhsTag;
use think\Db;
use think\Env;
use think\response\Json;

class UserConsultChat extends Auth
{
    private $appType2 = 2;

    /**
     * 获取 咨询对话 记录
     * @return Json
     * @throws \Exception
     */
    public function getConsultChatRecord()
    {
        $astrId = input('astr_id/d', 0);
        $minId = input('min_id/d', 0);
        if (!$astrId)
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        $astrInfo = (new ZlcrAstr())->getInfoById($astrId, ['nickname', 'avatar', 'extend']);
        if (!$astrInfo)
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        $consultChatIdModel = new ZyhsConsultChatRecord();
        $chatId = $consultChatIdModel->getChatIdByAstrId($this->appType2, $this->user['id'], $astrId);
        if ($minId === 0 && $chatId)
        {
            $chatIdInfo = $consultChatIdModel->getInfoById($chatId, ['msg_num']);
            if ($chatIdInfo['msg_num'] > 0)
            {   // 更新 未读消息数量
                $consultChatIdModel->updateData($chatId, ['msg_num' => 0], $this->appType2);
                $consultChatIdModel->setUserUnreadChatIdMsgNum($this->appType2, $this->user['id'], $chatId, 2, 0);
            }
            $zlcr3ConsultQuestionModel = new ZyhsConsultQuestion();
            $consultQuestionInfo = $zlcr3ConsultQuestionModel->getUserConsultQuestion($this->appType2, $this->user['id']);
            if ($consultQuestionInfo && isset($consultQuestionInfo['extend']['send_astro']) && $consultQuestionInfo['extend']['send_astro'])
            {
                foreach ($consultQuestionInfo['extend']['send_astro'] as $key => $item)
                {
                    if ((int)$item['astr_id'] === $astrId && $item['answer_id'] && !$item['is_read'])
                    {   // 有答案了 并且 未读
                        $consultQuestionInfo['extend']['send_astro'][$key]['is_read'] = 1;
                        // 更新 阅读状态
                        $zlcr3ConsultQuestionModel->updateData($consultQuestionInfo['id'], $this->appType2, $this->user['id'], ['extend' => json_encode($consultQuestionInfo['extend'], JSON_UNESCAPED_UNICODE)]);
                        break;
                    }
                }
            }
        }
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $resData = $consultChatRecordDetailsModel->getPageDatas($chatId, 10, $minId);
        if ($resData['data'])
        {
            $resData['data'] = $consultChatRecordDetailsModel->userDataListResert($resData['data'], $astrInfo, $this->user, $this->appType2, $delayComment);
        }
        if ((empty($resData['data']) && $minId === 0) || ($resData['data'] && $resData['surplus_num'] === 0))
        {
            $chatDefaultContent = $astrInfo['extend']['default_chat'] ?? "Hi，很高兴为你服务！\r\n你可以和我聊聊你的疑惑，或者直接向我咨询。";
            array_unshift($resData['data'], [
                'id' => 0,
                'type' => 2,
                'time_des' => '',
                'time' => 0,
                'avatar' => $astrInfo['avatar'],
                'msg_des' => '',
                'tags' => [],
                'consult_info' => null,
                'content' => $chatDefaultContent,
                'content_type' => 1,
                'btn_info' => null,
            ]);
        }
        // 占星师 昵称
        $resData['nickname'] = $astrInfo['nickname'];
        $numData = $consultChatRecordDetailsModel->getUserConsultAstrMsgNumByTodayEx($this->appType2, $this->user['id'], $astrId);
        $resData['num'] = min($numData['total'], $numData['num'], $numData['max_num']);
        $resData['delay_comment'] = $delayComment ?? null;
        $consultAccountInfo = (new Zlcr3ConsultAccount())->getInfoById($astrId);
        $resData['has_astro_skill'] = in_array(116, $consultAccountInfo['tags'], false) ? 1 : 0; // 是否具备 星盘 资格 1=>具备 0=>不具备;
        // 取发送 档案 价格
        $price = config('zyhsgoods.chat_send_recode_price');
        $resData['send_astr_coin'] = $price;
        $zhunleUserAccountModel = new ZhunleUserAccount();
        $userCoinInfo = $zhunleUserAccountModel->getUserCoinFromCache($this->user['id']);
        $resData['coin_num'] = (int)($userCoinInfo['balance'] ?? 0);// 准币余额
        $resData['coin_pwd_status'] = (isset($userCoinInfo['password']) && $userCoinInfo['password']) ? 1 : 0;  // 是否设置了支付密码
        $resData['is_can_appointment'] = (new ZlcrAstr())->getAstrAppointmentStatus($astrId);//默认隐藏预约按钮
        $resData['btn_name'] = sprintf("连线咨询（%d币/分钟）", $consultAccountInfo['price']);
        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 发送 咨询 消息
     * @return Json
     * @throws \Exception
     */
    public function sendConsultMsg()
    {
        $astrId = input('astr_id/d', 0);
        $type = input('type/d', 0);
        $content = input('content/s', '');

        if (!in_array($type, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (mb_strlen($content) > 100)
        {
            return show(config('code.error'), '消息内容过长，最多输入100字～');
        }

        if (Util::commentCheck($this->user['id'], ['action' => 'sendConsultMsg', 'type' => $type, 'astr_id' => $astrId, 'content' => $content], 5))
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        $consultAccountInfo = (new Zlcr3ConsultAccount())->getInfoById($astrId);
        $isConsult = $consultAccountInfo && $consultAccountInfo['consult_status'] === 1 ? 1 : 0;
        if (!$isConsult)
        {
            return show(config('code.error'), '服务异常，咨询师不存在～');
        }
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $numData = $consultChatRecordDetailsModel->getUserConsultAstrMsgNumByTodayEx($this->appType2, $this->user['id'], $astrId);
        $sendNum = min($numData['total'], $numData['num'], $numData['max_num']);
        if ($sendNum <= 0)
        {
            return show(config('code.error'), '机会已用尽，发送失败～');
        }
        $consultChatIdModel = new ZyhsConsultChatRecord();
        $chatId = $consultChatIdModel->getChatIdByAstrId($this->appType2, $this->user['id'], $astrId);

        $nowTimw = $this->request->time();
        if (!$chatId)
        {
            $insertData = [
                'app_type' => $this->appType2,
                'uid' => $this->user['id'],
                'astr_id' => $astrId,
                'last_chat_detail_id' => 0,
                'last_chat_detail_time' => 0,
                'create_time' => $nowTimw,
            ];
            // 创建新的会话
            $chatId = $consultChatIdModel->SaveData($insertData);
        }

        //阿里云内容审查
        if ($type === 1)
        {
            $res = AliyunFilterWord::checkText($content, 'voice_mic');
        } else
        {
            $oss = Env::get('host.photo');
            $res = AliyunFilterWord::checkImg(1, $oss . $content, 'voice_mic');
            if ($res['status'] === true)
            {
                $res = [];
            }
        }
        if ($res)
        {
            if ($res['level'] === 'review')
            {
                $interceptTips = $consultChatRecordDetailsModel->interceptTips;
                (new ZyhsConsultChatInterceptRecord())->saveData([
                    'type' => 2,
                    'level' => 1,
                    'content_type' => $type,
                    'chat_id' => $chatId,
                    'user_id' => $this->user['id'],
                    'content' => $content,
                    'reason' => $res['text'],
                    'create_time' => $this->request->time(),
                ]);
            } elseif ($res['level'] === 'block')
            {
                (new ZyhsConsultChatInterceptRecord())->saveData([
                    'type' => 2,
                    'level' => 2,
                    'content_type' => $type,
                    'chat_id' => $chatId,
                    'user_id' => $this->user['id'],
                    'content' => $content,
                    'reason' => $res['text'],
                    'create_time' => $this->request->time(),
                ]);
                return show(430, '发送失败，你所发送的内容中包含敏感信息。 注意不要泄露自己的联系方式和个人信息，以防上当受骗，平台将对你的个人隐私严格保密 。');
            }
        }
        $consultMsgData = [
            'chat_id' => $chatId,
            'app_type' => $this->appType2,
            'uid' => $this->user['id'],
            'astr_id' => $astrId,
            'type' => 2,    //  1=>APP消息 2=>用户发送消息
            'title' => '',
            'content' => $content, // 提问问题
            'data_type' => $type,   // 1=>普通消息  2=>图片  3=>语音咨询消息
            'extend' => ['intercept_tips' => isset($interceptTips) ? $res['text'] : ''],  //  语音咨询消息 ｜ 图片信息 | 内容拦截信息
            'pid' => 0, // 待更新
            'create_time' => $nowTimw,
        ];

        $resData = $consultChatRecordDetailsModel->SaveData($chatId, $consultMsgData);

        if ($resData)
        {   // 更新用户端 最后咨询信息
            $consultChatIdModel->updateData($chatId, [
                'uid' => $this->user['id'],
                'last_chat_detail_id' => $resData['id'],
                'last_chat_detail_time' => $nowTimw,
            ], $this->appType2);
            // 更新咨询师端 最后咨询信息
            $zlcr3ConsultChatRecordAstrModel = new ZyhsConsultChatRecordAstr();
            $astrChatInfo = $zlcr3ConsultChatRecordAstrModel->getUserAstrChatInfo($this->appType2, $this->user['id'], $astrId);
            $zlcr3ConsultChatRecordAstrModel->userSendUpdate($this->appType2, $this->user['id'], $astrId, [
                'last_chat_detail_id' => $resData['id'],
                'last_chat_detail_time' => $nowTimw,
                'user_last_msg_time' => $nowTimw,
                'unread_num' => Db::raw('unread_num + 1'),
                'question_num' => Db::raw('question_num + 1'),
                'delay_num' => Db::raw('delay_num + 1'),
            ]);
            $delayComment = null;
            $resData1 = current($consultChatRecordDetailsModel->userDataListResert([$resData], [], $this->user, $this->appType2, $delayComment));
            // 判断咨询师是否在线
            if (LiveMessage::getUserIsOnline(2, $astrId))
            {   // 向 咨询师发送消息
                $astrData2 = current($consultChatRecordDetailsModel->astrDataListResert([$resData], [], $this->user, $this->appType2));
                LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $astrId), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                    'msg_type' => 2,
                    'app_type' => $this->appType2,
                    'uid' => $this->user['id'],
                    'num' => $astrChatInfo['delay_num'] + 1,
                    'msg_data' => $astrData2,
                ]);
            }
            // 发送 咨询问题 数量增加
            $consultChatRecordDetailsModel->setUserConsultMsgAstrNumByTodayInc($this->appType2, $this->user['id'], $astrId);
            $resData1['time_des'] = '';
            $resData1['intercept_tips'] = $interceptTips ?? '';

            if ($type === 1)
            {
                $pushAlert = mb_strlen($content) > 25 ? mb_substr($content, 0, 25) : $content;
            } else
            {
                $pushAlert = '[图片]';
            }
            $pushData = [
                'action' => 'extend',
                'target' => 'local',
                'link' => "chat?id={$this->user['id']}&app_type={$this->appType2}",
                'pop_msg' => json_encode([
                    'avatar' => $this->user['avatar'],
                    'name' => $this->user['nickname'],
                    'msg' => $pushAlert,
                    'target' => 'local',
                    'link' => "chat?id={$this->user['id']}&app_type={$this->appType2}",
                    'uid' => $this->user['id'],
                    'app_type' => $this->appType2,
                ], JSON_UNESCAPED_UNICODE),
            ];
            (new AstrPush())->pushUserMsg($astrId, $pushAlert, $pushData);

            //咨询师默认回复队列添加
            Util::queuePush('user_consult_default_reply', ['chat_id' => $resData['id']], 120);

            return show(config('code.success'), '请求成功', $resData1);
        }

        return show(config('code.error'), '服务异常，请稍后再试～');
    }

    /**
     * 发送 咨询 问题
     * @return Json
     * @throws \Exception
     */
    public function sendConsultQuestion()
    {
        $question = trim(input('question/s', ''));

        if (empty($question))
        {
            return show(config('code.error'), '提交咨询问题不能为空～');
        }

        if (mb_strlen($question) > 100)
        {
            return show(config('code.error'), '提交咨询问题最多100字～');
        }

        // 判断当前是否 已经 提交过了
        $zlcr3ConsultQuestionModel = new ZyhsConsultQuestion();
        $consultQuestionInfo = $zlcr3ConsultQuestionModel->getUserConsultQuestion($this->appType2, $this->user['id']);
        if ($consultQuestionInfo)
        {
//            $t = 86400 - ($this->request->time() - $consultQuestionInfo['create_time']);
//            if ($t > 3600)
//            {
//                $t = (int)(round($t / 3600)) . '小时';
//            } else
//            {
//                $t = ceil(($t % 3600) / 60) . '分钟';
//            }
//
//            return show(config('code.error'), $t . '后才能再次提交咨询问题～');
            return show(config('code.error'), '已经提交过了');
        }

        //内容检测
        $res = AliyunFilterWord::checkText($question, 'voice_mic');
        if ($res)
        {
            if ($res['level'] === 'review')
            {
                $interceptTips = (new ZyhsConsultChatRecordDetails())->interceptTips;
            } elseif ($res['level'] === 'block')
            {
                return show(430, '发送失败，你所发送的内容中包含敏感信息。 注意不要泄露自己的联系方式和个人信息，以防上当受骗，平台将对你的个人隐私严格保密 。');
            }
        }

        $data = [
            'app_type' => $this->appType2,
            'uid' => $this->user['id'],
            'content' => $question,
            'extend' => [
                'intercept_tips' => isset($interceptTips) ? $res['text'] : '',
                'send_astro' => [],
            ],
            'create_time' => $this->request->time(),
        ];

        $id = $zlcr3ConsultQuestionModel->saveData($data);
        // 添加到队列
        Util::queuePush('send_consult_question', ['app_type' => $this->appType2, 'uid' => $this->user['id'], 'id' => $id], 10);

        return show(config('code.success'), '问题发送成功，请耐心等待咨询师回复。', [
            'toast' => '问题发送成功，请耐心等待咨询师回复。',
        ]);
    }

    /**
     * 【立即｜更换】咨询
     * @return Json
     * @throws \Exception
     */
    public function getAstrAsk()
    {
        $astrId = input('astr_id/d', 0);

        $testAccountConfig = (new ZyhsConfig())->configInfo('rtc');
        $testUser = $testAccountConfig['test_user'] ?? '';
        $testAstrId = $testUser ? explode(',', $testUser) : [];
        if (Util::ZyhsIsHuaweiOrHonorOrOppoHg(2))
        {   // 华为 合规情况 只显示 当前占星师数据
            if (Util::IsHuaweiAndOppo())
            {
                $astrIdList = $testAccountConfig['huawei_hg_consult_astr_ids'] ? explode(',', $testAccountConfig['huawei_hg_consult_astr_ids']) : [];
            } else
            {
                $astrIdList = $testAccountConfig['honor_hg_consult_astr_ids'] ? explode(',', $testAccountConfig['honor_hg_consult_astr_ids']) : [];
            }
            $astrIds = [];
            foreach ($astrIdList as $idItem)
            {
                if (!in_array($idItem, $testAstrId) && $astrId != $idItem)
                {
                    $astrIds[] = (int)$idItem;
                }
            }
            $data = $astrIds;
        } else
        {
            $data = (new ZyhsConsultAstrData())->getRankingList(2);
            if ($astrId && !isset($data[$astrId]))
            {
                $astrId = 0;
            } else
            {
                unset($data[$astrId]);
            }
            foreach ($testAstrId as $value)
            {
                unset($data[$value]);
            }
            $data = array_keys($data);
        }
        shuffle($data);
        $resAstrId = 0;
        $resData = [];
        $zlcrAstrModel = new ZlcrAstr();
        $zlcr3ConsultAccountModel = new Zlcr3ConsultAccount();
        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        if ($consultChatRtcRecordModel->getNowRtcDataByCache(1, $this->appType2, $this->user['id']))
        {
            return show(202, '正在连线中，不支持当前操作');
        }
        if (Util::ZyhsIsHuaweiOrHonorOrOppoHg(2))
        {
            $rtcConfig = (new ZyhsConfig())->configInfo('rtc');
            if (Util::IsHuaweiAndOppo())
            {
                if (isset($rtcConfig['huawei_work_intro']) && $rtcConfig['huawei_work_intro'])
                {
                    $workIntro = $rtcConfig['huawei_work_intro'];
                }
            } else
            {
                if (isset($rtcConfig['honor_work_intro']) && $rtcConfig['honor_work_intro'])
                {
                    $workIntro = $rtcConfig['honor_work_intro'];
                }
            }
        }
        while ($resAstrId === 0 && $data)
        {
            $astrIdItem = array_shift($data);
            $consultAstrInfo = $zlcr3ConsultAccountModel->getInfoById($astrIdItem);
            if ($consultAstrInfo['status'] === 1 && $consultAstrInfo['consult_status'] === 1)
            {   // 咨询师在线 并且 咨询状态正常
                // 判断是否正在连线
                $astrNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(2, $this->appType2, $astrIdItem);
                if (!$astrNowConsultRtcInfo)
                {
                    $resAstrId = $astrIdItem;
                    $astrInfo = $zlcrAstrModel->getInfoById($astrIdItem);
                    $coinNum = OrdersLib::getCoinNum($this->user['id']);  // 账户信息
                    $tip = '';
                    if ($consultAstrInfo['service_duration'] > 0)
                    {
                        $t = ceil($consultAstrInfo['service_duration'] / 60);
                        $tip .= '服务' . ($t > 200 ? '200+' : $t) . '分钟';
                    }
                    if ($consultAstrInfo['recommended_nums'] > 0)
                    {
                        if ($tip)
                        {
                            $tip .= '·';
                        }
                        $tip .= "{$consultAstrInfo['recommended_nums']}次被推荐";
                    }
                    $couponIds = (new UserCoupon())->getConsultRtcCids($this->user['id']);
                    // 获取新人福利 免充值 发起连线
                    $newUserWelfare = (new ZyhsConsultRtcUserBenefits())->getConsultRtcUserBenefits($this->appType2, $this->user['id']);
                    $freeRtcDuration = $newUserWelfare ? (($newUserWelfare['min'] ?? 0) * 60) : 0;
                    // 判断当前是否 已经 提交过了
                    $zlcr3ConsultQuestionModel = new ZyhsConsultQuestion();
                    $consultQuestionInfo = $zlcr3ConsultQuestionModel->getUserConsultQuestion($this->appType2, $this->user['id']);
                    $tags = $zlcr3ConsultAccountModel->getTags($consultAstrInfo['tags']);
                    if (Util::ZyhsIsHuaweiOrHonorOrOppoHg(2))
                    {
                        $tags = array_values(array_diff($tags, ['星盘']));
                    }
                    $resData = [
                        'avatar' => $astrInfo['avatar'],
                        'name' => $astrInfo['nickname'],
                        'tags_icon' => $zlcr3ConsultAccountModel->getTagsIcon($consultAstrInfo['tids']),
                        'tags' => $tags,
                        'user_coin' => $coinNum,
                        'price_coin' => $consultAstrInfo['price'],
                        'tip' => $tip,
                        'notice' => "你已确认自己为成年人，无精神疾病和自我伤害等倾向，并承诺在咨询过程中理性看待老师给出的建议，在咨询以外的一切其它行为与平台无关。\r\n连线需保证您的准币余额大于五分钟连麦消耗。\r\n请提前添加咨询所需的档案信息，以免浪费咨询时间。\r\n连麦开始1分钟内是免费试麦准备时间，如果出现声音问题请及时申请故障挂断，调试后重试。\r\n请保证网络正常，以免因网络问题影响你的咨询体验\r\n连麦咨询不支持退款，请谨慎购买，理性消费:为保证咨询服务的完整性，请尽量保证准币余额充足。",
                        'des' => $workIntro ?? ($astrInfo['extend']['work_intro'] ?? ''),    // 营业介绍
                        'btn_text' => $freeRtcDuration > 60 ? sprintf("免费咨询连线%d分钟", $newUserWelfare['min'] ?? 0) : '发起咨询(免费60秒)',
                        'astr_id' => $astrIdItem,
                        'has_coupon' => $couponIds ? 1 : 0,
                        'close_is_pop' => $consultQuestionInfo ? 0 : 1,
                        'level' => $consultAstrInfo['level'],
                        'has_astro_skill' => in_array(116, $consultAstrInfo['tags'], false) ? 1 : 0, // 是否具备 星盘 资格 1=>具备 0=>不具备
                        'free_rtc_duration' => $freeRtcDuration,
                    ];
                }
            }
        }
        if ($resData)
        {
            return show(config('code.success'), '请求成功', $resData);
        } else
        {
            if ($astrId)
            {
                return show(202, '当前咨询师较少，没有更多了');
            } else
            {
                return show(202, '当前咨询师较少，请稍后再试～');
            }
        }
    }

    /**
     * 获取 咨询对话记录 列表
     */
    public function getConsultChatIdList()
    {
        // if ($this->user)
        // {
        $zl6ConsultChatRecordModel = new ZyhsConsultChatRecord();
        $pageData = $zl6ConsultChatRecordModel->getListPage($this->user['id'], 'last_chat_detail_time', [], $this->appType2, 'desc', 0);
        $pageData['data'] = $zl6ConsultChatRecordModel->dataInit($pageData['data']);
        $pageData['data'] = $zl6ConsultChatRecordModel->pageDataResert($this->appType2, $pageData['data']);
        $pageData['msg_num'] = $zl6ConsultChatRecordModel->getUserUnreadAllNum($this->appType2, $this->user['id']); // 未读消息数量
        //    获取 反馈消息 数量
        $zyhsAppFeedbackModel = new ZyhsAppFeedback();
        $pageData['feedback_new'] = $zyhsAppFeedbackModel->getHasUnread(2, $this->user['id']) ? 1 : 0;
        // } else
        // {   // 未登录
        //     $pageData = [
        //         'total' => 0,// 记录总数
        //         'per_page' => 15,// 每页多少条
        //         'current_page' => 1,// 当前页数
        //         'last_page' => 1,// 总页数
        //         'data' => [],
        //         'msg_num' => 0,
        //         'feedback_new' => 0,
        //         'interact_msg' => [
        //             'msg_num' => 0,
        //             'des' => '暂无消息',
        //             'des_color' => '#5F5F79',
        //         ],
        //     ];
        // }
        return show(config('code.success'), '请求成功', $pageData);
    }

    /**
     * 删除 咨询对话记录
     * @return Json
     * @throws \Exception
     */
    public function delConsultChatId()
    {
        $astrId = input('astr_id/d', 0);
        $consultChatIdModel = new ZyhsConsultChatRecord();
        $chatId = $consultChatIdModel->getChatIdByAstrId($this->appType2, $this->user['id'], $astrId);
        if (!$chatId)
        {
            return show(config('code.success'), '会话记录已删除');
        }
        $res = $consultChatIdModel->delChat($this->appType2, $this->user['id'], $astrId, $chatId);
        if ($res)
        {
            $consultChatIdModel->setUserUnreadChatIdMsgNum($this->appType2, $this->user['id'], $chatId, 2, 0);

            return show(config('code.success'), '操作成功');
        }

        return show(config('code.error'), '服务异常，请稍后再试～');
    }

    /**
     * 向 会话占星师发送 星盘
     * @return Json
     * @throws \Exception
     */
    public function chatSendRecode()
    {
        $astrId = input('astr_id/d', 0);
        $rid = input('rid/d', 0);
        $password = input('password/s', '');
        if (!$astrId || !$rid)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (Util::commentCheck($this->user['id'], ['action' => 'chatSendRecode', 'rid' => $rid, 'astr_id' => $astrId], 5))
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        $recodeModel = new Recode();
        $recode = $recodeModel->getInfoById($rid);
        if (!$recode || $recode['uid'] != $this->user['id'] || $recode['status'] != 1)
        {
            return show(config('code.error'), '服务异常,档案不存在～');
        }
        $consultAccountInfo = (new Zlcr3ConsultAccount())->getInfoById($astrId);
        $isConsult = $consultAccountInfo && $consultAccountInfo['consult_status'] === 1 ? 1 : 0;
        if (!$isConsult)
        {
            return show(config('code.error'), '服务异常，咨询师不存在～');
        }
        $consultChatIdModel = new ZyhsConsultChatRecord();
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $chatId = $consultChatIdModel->getChatIdByAstrId($this->appType2, $this->user['id'], $astrId);
        $nowTime = $this->request->time();
        if (!$chatId)
        {
            $insertData = [
                'app_type' => $this->appType2,
                'uid' => $this->user['id'],
                'astr_id' => $astrId,
                'last_chat_detail_id' => 0,
                'last_chat_detail_time' => 0,
                'create_time' => $nowTime,
            ];
            // 创建新的会话
            $chatId = $consultChatIdModel->SaveData($insertData);
        }
        // 取发送 档案 价格
        $price = config('zyhsgoods.chat_send_recode_price');
        $zhunleUserAccountModel = new ZhunleUserAccount();
        $userCoinInfo = $zhunleUserAccountModel->getUserCoinFromCache($this->user['id']);
        $zhunleUserAccountModel->verifyCoinPay($userCoinInfo, $password, $price);
        $coinNum = (int)($userCoinInfo['balance'] ?? 0);// 准币余额
        // 扣除 准币
        $coinNum = $coinNum - $price;
        $consume_price = $userCoinInfo['consume_price'] + OrdersLib::getOrderCoinTotalAmount($price);
        $consume_coin = $userCoinInfo['consume_coin'] + $price;
        //更新用户钱包金额
        $zhunleUserAccountModel->UpdateData($this->user['id'], ['balance' => $coinNum, 'consume_price' => $consume_price, 'consume_coin' => $consume_coin, 'update_time' => $nowTime], ['uid' => $this->user['id']]);
        // 写入 用户 准币流水
        $insertData = [
            'status' => 1,
            'account' => 0,
            'uid' => $this->user['id'],
            'consumer_type' => 2,
            'order_type' => 110,
            'gid' => 0,
            'pray_date' => 0,
            'total_amount' => $price / 10,
            'coin_num' => $price,
            'balance' => $coinNum,
            'order_id' => '',
            'trade_type' => 4,
            'create_time' => $nowTime,
            'extend' => '[]',
        ];
        //增加准币明细记录
        $zhunleUserAccountRecordModel = new ZhunleUserAccountRecord();
        $crid = $zhunleUserAccountRecordModel->SaveData($this->user['id'], $insertData);
        $utilModel = new Util();
        $sendRecodeInfo = [
            'rid' => $rid,
            'year' => $recode['year'],
            'month' => $recode['month'],
            'day' => $recode['day'],
            'sun' => $utilModel->recodeAstroMiddlehand($recode['sun']),
            'moon' => $utilModel->recodeAstroMiddlehand($recode['moon']),
            'asc' => $utilModel->recodeAstroMiddlehand($recode['asc']),
        ];
        $consultMsgData = [
            'chat_id' => $chatId,
            'app_type' => $this->appType2,
            'uid' => $this->user['id'],
            'astr_id' => $astrId,
            'type' => 2,    //  1=>APP消息 2=>用户发送消息
            'title' => '',
            'content' => '', // 提问问题
            'data_type' => 8,   // 1=>普通消息  2=>图片  3=>语音咨询消息  4=>咨询问题  5=>咨询问题答案 6=>问答悬赏问题回复 7=>问答悬赏追问已回复 8=>用户发送星盘信息
            'extend' => ['intercept_tips' => '', 'recode_info' => $sendRecodeInfo],  //  语音咨询消息 ｜ 图片信息 | 内容拦截信息
            'pid' => 0, // 待更新
            'create_time' => $nowTime,
        ];
        $resData = $consultChatRecordDetailsModel->SaveData($chatId, $consultMsgData);
        if ($resData)
        {   // 更新用户端 最后咨询信息
            $consultChatIdModel->updateData($chatId, [
                'uid' => $this->user['id'],
                'last_chat_detail_id' => $resData['id'],
                'last_chat_detail_time' => $nowTime,
            ], $this->appType2);
            $zhunleUserAccountRecordModel->UpdateData($this->user['id'], $crid, ['extend' => json_encode(['chat_detail_id' => $resData['id']], JSON_UNESCAPED_UNICODE)], ['id' => $crid]);
            // 更新咨询师端 最后咨询信息
            $zlcr3ConsultChatRecordAstrModel = new ZyhsConsultChatRecordAstr();
            $astrChatInfo = $zlcr3ConsultChatRecordAstrModel->getUserAstrChatInfo($this->appType2, $this->user['id'], $astrId);
            $zlcr3ConsultChatRecordAstrModel->userSendUpdate($this->appType2, $this->user['id'], $astrId, [
                'last_chat_detail_id' => $resData['id'],
                'last_chat_detail_time' => $nowTime,
                'unread_num' => Db::raw('unread_num + 1'),
                'delay_num' => Db::raw('delay_num + 1'),
            ]);
            $resData1 = current($consultChatRecordDetailsModel->userDataListResert([$resData], [], $this->user, $this->appType2));
            // 判断咨询师是否在线
            if (LiveMessage::getUserIsOnline(2, $astrId))
            {   // 向 咨询师发送消息
                $astrData2 = current($consultChatRecordDetailsModel->astrDataListResert([$resData], [], $this->user, $this->appType2));
                LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $astrId), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                    'msg_type' => 2,
                    'app_type' => $this->appType2,
                    'uid' => $this->user['id'],
                    'num' => $astrChatInfo['delay_num'] + 1,
                    'msg_data' => $astrData2,
                ]);
            }
            $resData1['time_des'] = '';
            $resData1['intercept_tips'] = '';
            $resData1['transaction_id'] = $crid;

            $pushAlert = '[星盘]';
            $pushData = [
                'action' => 'extend',
                'target' => 'local',
                'link' => "chat?id={$this->user['id']}&app_type={$this->appType2}",
                'pop_msg' => json_encode([
                    'avatar' => $this->user['avatar'],
                    'name' => $this->user['nickname'],
                    'msg' => $pushAlert,
                    'target' => 'local',
                    'link' => "chat?id={$this->user['id']}&app_type={$this->appType2}",
                    'uid' => $this->user['id'],
                    'app_type' => $this->appType2,
                ], JSON_UNESCAPED_UNICODE),
            ];
            (new AstrPush())->pushUserMsg($astrId, $pushAlert, $pushData);

            return show(config('code.success'), '请求成功', $resData1);
        }

        return show(config('code.error'), '服务异常，请稍后再试～');
    }

    /**
     * 发起 RTC连麦 交互请求
     * @return Json
     * @throws \Exception
     */
    public function requestRtcInteraction()
    {
        $astrId = input('astr_id/d', 0);
        $zlcrAstrModel = new ZlcrAstr();
        if (Util::commentCheck($this->user['id'], ['action' => 'requestRtcInteraction', 'astr_id' => $astrId], 5))
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        $consultAccountInfo = (new Zlcr3ConsultAccount())->getInfoById($astrId);
        $isConsult = $consultAccountInfo && $consultAccountInfo['consult_status'] === 1 ? 1 : 0;
        if (!$isConsult)
        {
            return show(config('code.error'), '服务异常，咨询师不存在～');
        }
        // 获取当前用户 咨询状态
        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        $userNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(1, $this->appType2, $this->user['id']);
        if ($userNowConsultRtcInfo)
        {   // 用户正在连麦中
            return show(config('code.error'), '当前正在连线中，不可重复连线～');
        }
        // 咨询师营业状态判断 不是ws在线状态
        if ($consultAccountInfo['status'] !== 1)
        {   // 咨询师休息 了
            return show(config('code.error'), '咨询师暂时不在，稍侯再来吧~');
        }
        // 获取当前咨询师 咨询状态
        $astrNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(2, $this->appType2, $astrId);
        if ($astrNowConsultRtcInfo)
        {   // 咨询师 当前正在 连麦中 或者 已经有连麦请求
            $extend = [
                'rtc_data' => [
                    'rtc_id' => 0,
                    'status' => 5,  //【rtc_id=0该字段数据生效】 1=>申请中待接听  2=>咨询师未响应  3=>咨询师拒绝  4=>连线已取消 5=>咨询师忙线中
                ],
            ];
            $isRtc = false;
        } else
        {
            $extend = [
                'rtc_data' => [
                    'rtc_id' => 0,
                    'status' => 1,  //【rtc_id=0该字段数据生效】 1=>申请中待接听  2=>咨询师未响应  3=>咨询师拒绝  4=>连线已取消 5=>咨询师忙线中
                ],
            ];
            $isRtc = true;
        }
        $consultChatIdModel = new ZyhsConsultChatRecord();
        $chatId = $consultChatIdModel->getChatIdByAstrId($this->appType2, $this->user['id'], $astrId);
        $nowTimw = $this->request->time();
        if (!$chatId)
        {
            $insertData = [
                'app_type' => $this->appType2,
                'uid' => $this->user['id'],
                'astr_id' => $astrId,
                'last_chat_detail_id' => 0,
                'last_chat_detail_time' => 0,
                'create_time' => $nowTimw,
            ];
            // 创建新的会话
            $chatId = $consultChatIdModel->SaveData($insertData);
        }

        $consultMsgData = [
            'chat_id' => $chatId,
            'app_type' => $this->appType2,
            'uid' => $this->user['id'],
            'astr_id' => $astrId,
            'type' => 2,    //  1=>APP消息 2=>用户发送消息
            'title' => '',
            'content' => '', // 提问问题
            'data_type' => 3,   // 1=>普通消息  2=>图片  3=>语音咨询消息
            'extend' => $extend,  //  语音咨询消息 ｜ 图片信息
            'pid' => 0, // 待更新
            'create_time' => $nowTimw,
        ];

        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $resData = $consultChatRecordDetailsModel->SaveData($chatId, $consultMsgData);
        if ($resData)
        {
            $consultChatIdModel->updateData($chatId, [
                'uid' => $this->user['id'],
                'last_chat_detail_id' => $resData['id'],
                'last_chat_detail_time' => $nowTimw,
            ], $this->appType2);
            // 更新咨询师端 最后咨询信息
            (new ZyhsConsultChatRecordAstr())->userSendUpdate($this->appType2, $this->user['id'], $astrId, [
                'last_chat_detail_id' => $resData['id'],
                'last_chat_detail_time' => $nowTimw,
                'unread_num' => Db::raw('unread_num + 1'),
                'call_num' => Db::raw('call_num + 1'),
            ]);

            $resData2 = current($consultChatRecordDetailsModel->userDataListResert([$resData], [], $this->user, $this->appType2));
            if ($isRtc)
            {   // 更新用户端 最后咨询信息
                $astrInfo = $zlcrAstrModel->getInfoById($astrId, ['avatar', 'nickname', 'tel']);
                $userNowConsultRtcInfo = [
                    'id' => 0, // 连麦ID    ID==0 为邀请连麦  否则为主播接受连麦
                    'rtc_sign' => uniqid('', false),
                    'app_type' => $this->appType2,
                    'astr_id' => $astrId,
                    'nickname' => $astrInfo['nickname'] ?? '',
                    'avatar' => $astrInfo['avatar'] ?? '',
                    'status' => 1,  // 当前连麦状态 1=>等待咨询师接受 2=>咨询师接受开始连麦中 3=>连麦成功 连麦中
                    'request_time' => $this->request->time(),   // 邀请咨询师连麦时间
                    'chat_id' => $resData['id'],
                ];
                $consultChatRtcRecordModel->saveNowRtcDataToCache(1, $this->appType2, $this->user['id'], $userNowConsultRtcInfo, false, $resData['id']);
                $astrNowConsultRtcInfo = [
                    'id' => 0, // 连麦ID    ID==0 为邀请连麦  否则为主播接受连麦
                    'rtc_sign' => $userNowConsultRtcInfo['rtc_sign'],
                    'app_type' => $this->appType2,
                    'uid' => $this->user['id'],
                    'nickname' => $this->user['nickname'] ?? '',
                    'avatar' => $this->user['avatar'] ?? '',
                    'uen' => $this->user['uen'] ?? '',
                    'status' => 1,  // 当前连麦状态 1=>等待咨询师接受 2=>咨询师接受开始连麦中 3=>连麦成功 连麦中
                    'request_time' => $this->request->time(),   // 邀请咨询师连麦时间
                    'chat_id' => $resData['id'],
                ];
                $astrNowConsultRtcInfo['recode_datas'] = $consultChatRecordDetailsModel->getRtcInitRecodeInfo($chatId);
                $consultChatRtcRecordModel->saveNowRtcDataToCache(2, $this->appType2, $astrId, $astrNowConsultRtcInfo, false, $resData['id']);
                // 判断咨询师是否在线
                if (LiveMessage::getUserIsOnline(2, $astrId))
                {   // 在线
                    $astrData = current($consultChatRecordDetailsModel->astrDataListResert([$resData], [], $this->user, $this->appType2));
                    LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $astrId), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                        'msg_type' => 2,
                        'app_type' => $this->appType2,
                        'uid' => $this->user['id'],
                        'msg_data' => $astrData,
                    ]);
                    $newUserWelfare = (new ZyhsConsultRtcUserBenefits())->getConsultRtcUserBenefits($this->appType2, $this->user['id']);
                    $freeRtcMin = $newUserWelfare['min'] ?? 0;
                    $desc = $freeRtcMin ? sprintf("申请语音咨询(免费%d分钟)…", $freeRtcMin) : '申请语音咨询…';
                    $voiceCallData = [
                        'chat_id' => $resData['id'],
                        'app_type' => $this->appType2,
                        'uid' => $this->user['id'],
                        'avatar' => $this->user['avatar'],
                        'nickname' => $this->user['nickname'],
                        'status' => 1,
                        'desc' => $desc,
                    ];
                    LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $astrId), LiveMessage::MSG_TYPE_POP_VOICE_CONSULT_CALL, $voiceCallData);
                } else
                {   // 咨询师ws不在线
                    AliyunPhone::singleCallByTts($astrInfo['tel'], 'TTS_282195080');
                }
                // 2分钟后 判断状态是否还是待接听 状态 如果是待接听状态 则取消连线
                Util::queuePush('rtc_consult_accept_check', ['id' => $resData['id']], 120);
            }
            $pushData = ['action' => 'extend', 'target' => 'local', 'link' => 'empty',];
            (new AstrPush())->pushUserMsg($astrId, '你收到新的咨询连线申请，点击查看', $pushData);
            $resData2['time_des'] = '';
            //  增加咨询师 可回复次数
            $zyhsConsultChatRecordAstrModel = new ZyhsConsultChatRecordAstr();
            $astrChatId = $zyhsConsultChatRecordAstrModel->getIdByAstrIdAndUid($astrId, $this->appType2, $this->user['id']);
            $astrChatIdInfo = $zyhsConsultChatRecordAstrModel->getInfoById($astrChatId);
            if ($astrChatIdInfo['call_delay_num'] < 3)
            {
                $astrChatIdInfo['call_delay_num'] = 3;
                $zyhsConsultChatRecordAstrModel->UpdateData($astrChatId, $astrId, [
                    'call_delay_num' => 3,
                ]);
            }
            return show(config('code.success'), '请求成功', $resData2);
        }

        return show(config('code.error'), '服务异常，请稍后再试～');
    }

    /**
     * 挂断连线｜取消连线（未接听）
     * @return Json
     * @throws \Exception
     */
    public function rtcCancel()
    {
        $chatDetailid = input('id/d', 0);
        $type = input('type/d', 0);
        $reason = input('reason/s', '');
        if (!$chatDetailid)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (Util::commentCheck($this->user['id'], ['action' => 'rtcCancel', 'id' => $chatDetailid, 'type' => $type, 'reason' => $reason], 5))
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        // 获取当前用户 咨询状态
        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $userNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(1, $this->appType2, $this->user['id']);
        $astrWsIsOnline = false;
        if ($userNowConsultRtcInfo)
        {   // 用户正在连麦中
            $res = $consultChatRtcRecordModel->setRtcPadlock($chatDetailid);
            if (!$res)
            {
                return show(config('code.error'), '连线状态异常，请稍后再试～');
            }
            if ((int)$userNowConsultRtcInfo['chat_id'] === $chatDetailid)
            {   // 删除当前连麦 信息
                $astrId = (int)$userNowConsultRtcInfo['astr_id'];
                // 更新当前连麦信息
                $astrNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(2, $this->appType2, $astrId);
                if ($astrNowConsultRtcInfo && (int)$astrNowConsultRtcInfo['chat_id'] === $chatDetailid)
                {   // 当前连麦数据正确
                    if (LiveMessage::getUserIsOnline(2, $astrId))
                    {   //  隐藏 电话提醒
                        $astrWsIsOnline = true;
                        $voiceCallData = [
                            'chat_id' => $chatDetailid,
                            'app_type' => $this->appType2,
                            'uid' => $this->user['id'],
                            'avatar' => $this->user['avatar'],
                            'nickname' => $this->user['nickname'],
                            'status' => 0,
                            'desc' => '',
                        ];
                        LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $astrId), LiveMessage::MSG_TYPE_POP_VOICE_CONSULT_CALL, $voiceCallData);
                    }
                }
                $chatDetail = $consultChatRecordDetailsModel->getInfoById($chatDetailid);
                if ($userNowConsultRtcInfo['id'])
                {   // 连线成功
                    $data = $consultChatRtcRecordModel->rtcConsultHangUp($chatDetail, $reason, 1, 1);
                    if ($data['status'])
                    {   // 删除 频道订阅 与 当前RTC房间
                        (new AliyunRtc())->rmEventSubAndDelRtcChannel('consult_' . $userNowConsultRtcInfo['id']);
                        // 返回 打点信息
                        // $data['data']['event_marking_data'] = $data['event_marking_data'];
                        $consultChatRtcRecordModel->loseOperatorLicense($chatDetailid);
                        return show(config('code.success'), '请求成功', $data['data']);
                    }

                    $consultChatRtcRecordModel->delNowRtcDataByCache(1, $this->appType2, $this->user['id'], $chatDetailid); // 删除当前连麦信息
                    $consultChatRtcRecordModel->loseOperatorLicense($chatDetailid);
                    return show(config('code.error'), $data['msg']);
                }
                // 未连线成功
                $consultChatRtcRecordModel->delNowRtcDataByCache(1, $this->appType2, $this->user['id'], $chatDetailid);
                if ($astrNowConsultRtcInfo && (int)$astrNowConsultRtcInfo['uid'] === $this->user['id'])
                {
                    $consultChatRtcRecordModel->delNowRtcDataByCache(2, $this->appType2, $astrId, $chatDetailid);
                }
                $chatDetail['extend']['rtc_data']['status'] = 4;  //【rtc_id=0该字段数据生效】 1=>申请中待接听  2=>咨询师未响应  3=>咨询师拒绝  4=>连线已取消 5=>咨询师忙线中
                // 更新数据
                $consultChatRecordDetailsModel->UpdateData($chatDetailid, ['extend' => $chatDetail['extend']]);
                $resData2 = current($consultChatRecordDetailsModel->userDataListResert([$chatDetail], [], $this->user, $this->appType2));

                $consultChatRecordAstrModel = new ZyhsConsultChatRecordAstr();
                $userChatId = $consultChatRecordAstrModel->getIdByAstrIdAndUid($astrId, $this->appType2, $this->user['id']);
                if ($userChatId)
                {
                    $userChatInfo = $consultChatRecordAstrModel->getInfoById($userChatId, 'unread_num');
                    if ($userChatInfo['unread_num'] === 0)
                    {   // 更新咨询师端 最后咨询信息
                        $consultChatRecordAstrModel->userSendUpdate($this->appType2, $this->user['id'], $astrId, [
                            'unread_num' => Db::raw('unread_num + 1'),
                        ]);
                    }
                }

                if ($astrWsIsOnline)
                {
                    $astrData = current($consultChatRecordDetailsModel->astrDataListResert([$chatDetail], [], $this->user, $this->appType2));
                    LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $astrId), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                        'msg_type' => 2,
                        'app_type' => $this->appType2,
                        'uid' => $this->user['id'],
                        'msg_data' => $astrData,
                    ]);
                }
                $resData2['event_marking_data'] = null;
                $consultChatRtcRecordModel->loseOperatorLicense($chatDetailid);
                return show(config('code.success'), '取消成功', $resData2);
            }
            $consultChatRtcRecordModel->loseOperatorLicense($chatDetailid);
            return show(config('code.error'), '语音连线咨询状态异常，请稍后再试～');
        }

        return show(config('code.error'), '语音连线咨询状态异常，请稍后再试～');
    }

    /**
     * 获取连线咨询状态
     * @return Json
     * @throws \Exception
     */
    public function getRtcConsultStatusInfo()
    {
        $astrId = input('astr_id/d', 0);
        $chatDetailId = input('id/d', 0);

        $zlcrAstrModel = new ZlcrAstr();
        $zlcr3ConsultAccountModel = new Zlcr3ConsultAccount();
        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();

        $chatDetail = null;
        if ($chatDetailId)
        {
            $chatDetail = $consultChatRecordDetailsModel->getInfoById($chatDetailId);
            if (!$chatDetail)
            {
                return show(config('code.error'), '请求异常，咨询信息不存在～');
            }

            $userNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(1, $this->appType2, $this->user['id']);
            if ($userNowConsultRtcInfo && (int)$userNowConsultRtcInfo['chat_id'] === $chatDetailId && $userNowConsultRtcInfo['status'] < 3)
            {
                $chatDetail = null;
            }
        } else
        {
            $consultAccountInfo = (new Zlcr3ConsultAccount())->getInfoById($astrId);
            $isConsult = $consultAccountInfo && $consultAccountInfo['consult_status'] === 1 ? 1 : 0;
            if (!$isConsult)
            {
                return show(config('code.error'), '服务异常，咨询师不存在');
            }
            // 获取当前 连线信息
            $userNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(1, $this->appType2, $this->user['id']);
            if ($userNowConsultRtcInfo)
            {   // 用户当前连线信息
                if ((int)$userNowConsultRtcInfo['astr_id'] !== $astrId)
                {
                    return show(config('code.error'), '你当前正在连线中，不可重复连线。');
                }
                if ((int)$userNowConsultRtcInfo['status'] === 3)
                {    // 当前连麦状态 1=>等待咨询师接受 2=>咨询师接受开始连麦中 3=>连麦成功 连麦中
                    // 当前正在连麦中
                    $chatDetail = $consultChatRecordDetailsModel->getInfoById($userNowConsultRtcInfo['chat_id']);
                }
                $chatDetailId = (int)$userNowConsultRtcInfo['chat_id'];
            }
        }

        $UserAccountModel = new ZhunleUserAccount();
        if ($chatDetail)
        {
            $rtcId = $chatDetail['extend']['rtc_data']['rtc_id'] ?? 0;
            if (!$rtcId)
            {
                return show(config('code.error'), '服务异常，请稍后再试～');
            }
            $avatar = $userNowConsultRtcInfo['avatar'] ?? '';
            $nickname = $userNowConsultRtcInfo['nickname'] ?? '';
            if (!$userNowConsultRtcInfo)
            {
                $astrInfo = $zlcrAstrModel->getInfoById($astrId, ['avatar', 'nickname']);
                $avatar = $astrInfo['avatar'];
                $nickname = $astrInfo['nickname'];
            }
            // 获取当前 连线信息
            $rtcInfo = $consultChatRtcRecordModel->getInfoById($rtcId);

            switch ($rtcInfo['status'])
            {   //  2=>连接中  3=>连麦中 4=>连麦结束 5=>故障挂断 6=>取消连麦（连接中挂断）
                case 3: // 3=>连麦中
                    $astrNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(2, $this->appType2, $astrId);
                    $user_coin = $UserAccountModel->getUserCoinFromCache($this->user['id']);  // 账户信息
                    $coinNum = (int)($user_coin['balance'] ?? 0);// 准币余额
                    $resData = [
                        'status' => 21,
                        'duration' => $this->request->time() - $rtcInfo['start_time'],
                        'test_duration' => $rtcInfo['test_duration'],
                        'user_coin' => $coinNum,                // 用户剩余准币数量
                        'used_coin' => $rtcInfo['coin'],        // 用户已经使用准币数量
                        'price_coin' => $rtcInfo['unit_price'], // 单价
                        'details' => $consultChatRtcRecordModel->resetRtcConsultStatusData($astrNowConsultRtcInfo ?? []),
                        'free_rtc_duration' => $rtcInfo['extend']['free_rtc_duration'] ?? 0,    // 新人福利 免费连线时长【秒】
                    ];
                    break;
                case 4: // 4=>连麦结束
                case 5: // 5=>故障挂断
                    if ($rtcInfo['duration'] >= 300)
                    {   // 连线时长 大于等于 5分钟
                        $resData = [
                            'status' => 31,
                            'duration' => $rtcInfo['duration'],
                            'coin' => $rtcInfo['coin'],
                            'avatar' => $avatar,
                            'name' => $nickname,
                            'id' => $chatDetailId,
                        ];
                    } else
                    {
                        $resData = [
                            'status' => 32,
                            'duration' => $rtcInfo['duration'],
                            'coin' => $rtcInfo['coin'],
                            'id' => $chatDetailId,
                            'list' => [
                                [
                                    'title' => '本次消耗详情',
                                    'des' => '',
                                    'type' => 1,
                                ], [
                                    'title' => '服务编号',
                                    'des' => "$chatDetailId",
                                    'type' => 2,
                                ], [
                                    'title' => '咨询师单价',
                                    'des' => $rtcInfo['unit_price'] . '准币/分钟',
                                    'type' => 1,
                                ], [
                                    'title' => '连线时长',
                                    'des' => gmdate("H:i:s", $rtcInfo['duration']),
                                    'type' => 1,
                                ],
                            ],
                        ];

                        if (isset($rtcInfo['extend']['cid']))
                        {
                            $userCouponAttr = (new UserCoupon())->getInfoById($rtcInfo['extend']['cid']);
                            $desc = "免费{$userCouponAttr['discount']}分钟（优惠券）";
                            if ($userCouponAttr['condition'] > 0)
                            {
                                $desc = "满{$userCouponAttr['condition']}分钟，" . $desc;
                            }
                            $resData['list'][] = [
                                'title' => '优惠',
                                'des' => $desc,
                                'type' => 1,
                            ];
                        }

                        if (isset($rtcInfo['extend']['free_rtc_duration']) && $rtcInfo['extend']['free_rtc_duration'] > $rtcInfo['test_duration'])
                        {   // 连线福利
                            $resData['list'][] = [
                                'title' => '连线福利',
                                'des' => sprintf("免费%d分钟", (int)($rtcInfo['extend']['free_rtc_duration'] / 60)),
                                'type' => 1,
                            ];
                        }

                        $resData['list'][] = [
                            'title' => '连线消耗',
                            'des' => $rtcInfo['coin'] . '准币',
                            'type' => 1,
                        ];
                    }
                    break;
                case 6:
                    $consultAccountInfo = (new Zlcr3ConsultAccount())->getInfoById($astrId);
                    $resData = [
                        'status' => 31,
                        'duration' => 0,
                        'coin' => 0,
                        'avatar' => $avatar,
                        'name' => $nickname,
                        'id' => $chatDetailId,
                        'level' => $consultAccountInfo['level'],
                    ];
                    break;
                default:
                    return show(config('code.error'), '服务异常，请稍后再试～');
            }
        } else
        {
            // 当前 没有连麦
            $astrInfo = $zlcrAstrModel->getInfoById($astrId);
            $consultAccount = $zlcr3ConsultAccountModel->getInfoById($astrId);
            // 获取新人福利 免充值 发起连线
            $newUserWelfare = (new ZyhsConsultRtcUserBenefits())->getConsultRtcUserBenefits($this->appType2, $this->user['id']);
            $freeRtcDuration = $newUserWelfare ? (($newUserWelfare['min'] ?? 0) * 60) : 0;

            if (isset($userNowConsultRtcInfo) && $userNowConsultRtcInfo)
            {   // 当前正在连线
                if ((int)$userNowConsultRtcInfo['status'] === 1)
                {   //  1=>等待咨询师接受
                    $status = 12;
                    $btnText = '等待咨询师响应';
                } else
                {   //  2=>咨询师接受开始连麦中
                    $status = 13;
                    $btnText = '连接中';
                }
            } else
            {   // 当前没有连线信息
                if ($consultAccount['status'] === 1)
                {   // 在线
                    $status = 0;
                    if ($freeRtcDuration > 60)
                    {
                        $btnText = sprintf("免费咨询连线%d分钟", $newUserWelfare['min']);
                    } else
                    {
                        $btnText = '申请连线咨询（免费试麦60秒）';
                    }
                } else
                {   // 休息
                    $status = 1;
                    // $btnText = '咨询师休息中，请稍后再来';
                    $btnText = '休息中，请预沟通留言';
                }
            }
            $tip = '';
            if ($consultAccount['service_duration'] > 0)
            {
                $t = ceil($consultAccount['service_duration'] / 60);
                $tip .= '服务' . ($t > 200 ? '200+' : $t) . '分钟';
            }
            if ($consultAccount['recommended_nums'] > 0)
            {
                if ($tip)
                {
                    $tip .= '·';
                }
                $tip .= "{$consultAccount['recommended_nums']}次被推荐";
            }

            $user_coin = $UserAccountModel->getUserCoinFromCache($this->user['id']);  // 账户信息
            $coinNum = (int)($user_coin['balance'] ?? 0);// 准币余额
            $coinPwdStatus = (isset($user_coin['password']) && $user_coin['password']) ? 1 : 0;  // 是否设置了支付密码

            $couponIds = (new UserCoupon())->getConsultRtcCids($this->user['id']);
            if (Util::ZyhsIsHuaweiOrHonorOrOppoHg(2))
            {
                $rtcConfig = (new ZyhsConfig())->configInfo('rtc');
                if (Util::IsHuaweiAndOppo())
                {
                    if (isset($rtcConfig['huawei_work_intro']) && $rtcConfig['huawei_work_intro'])
                    {
                        $workIntro = $rtcConfig['huawei_work_intro'];
                    }
                } else
                {
                    if (isset($rtcConfig['honor_work_intro']) && $rtcConfig['honor_work_intro'])
                    {
                        $workIntro = $rtcConfig['honor_work_intro'];
                    }
                }
            }

            $tags = $zlcr3ConsultAccountModel->getTags($consultAccount['tags']);
            if (Util::ZyhsIsHuaweiOrHonorOrOppoHg(2))
            {
                $tags = array_values(array_diff($tags, ['星盘']));
            }
            $resData = [
                'status' => $status,
                'avatar' => $astrInfo['avatar'],
                'name' => $astrInfo['nickname'],
                'tags_icon' => $zlcr3ConsultAccountModel->getTagsIcon($consultAccount['tids']),
                'tags' => $tags,
                'user_coin' => $coinNum,
                'is_set_password' => $coinPwdStatus,
                'price_coin' => $consultAccount['price'],
                'tip' => $tip,
                'notice' => "你已确认自己为成年人，无精神疾病和自我伤害等倾向，并承诺在咨询过程中理性看待老师给出的建议，在咨询以外的一切其它行为与平台无关。\r\n连线需保证您的准币余额大于五分钟连麦消耗。\r\n请提前添加咨询所需的档案信息，以免浪费咨询时间。\r\n连麦开始1分钟内是免费试麦准备时间，如果出现声音问题请及时申请故障挂断，调试后重试。\r\n请保证网络正常，以免因网络问题影响你的咨询体验\r\n连麦咨询不支持退款，请谨慎购买，理性消费:为保证咨询服务的完整性，请尽量保证准币余额充足。",
                'des' => $workIntro ?? ($astrInfo['extend']['work_intro'] ?? ''),    // 营业介绍
                'btn_text' => $btnText,
                'id' => $chatDetailId ?? 0,
                'has_coupon' => $couponIds ? 1 : 0,
                'level' => $consultAccount['level'],
                'has_astro_skill' => in_array(116, $consultAccount['tags'], false) ? 1 : 0, // 是否具备 星盘 资格 1=>具备 0=>不具备
                'free_rtc_duration' => $freeRtcDuration,
            ];
        }

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 更新连线咨询信息
     * @return Json
     * @throws \Exception
     */
    public function updateRtcConsultShareData()
    {
        $chatDetailId = input('id/d', 0);
        $recodeDatas = input('recode_datas/s', '');
        $diceDatas = input('dice_datas/s', '');
        $tarotDatas = input('tarot_datas/s', '');
        $type = input('type/d', 0);
        if (!$chatDetailId || !in_array($type, [1, 2, 3], true))
        {
            return show(config('code.error'), '请求异常，操作失败');
        }

        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();

        $chatDetail = $consultChatRecordDetailsModel->getInfoById($chatDetailId);

        if (!$chatDetail || $chatDetail['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，当前咨询不存在～');
        }
        $astrId = $chatDetail['astr_id'];
        $astrNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(2, $this->appType2, $astrId);

        if (!$astrNowConsultRtcInfo || (int)$astrNowConsultRtcInfo['chat_id'] !== $chatDetailId)
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }

        $updateData = [];
        switch ($type)  // //  1=>星盘 2=>骰子 3=>塔罗
        {
            case 1: //  1=>星盘
                $recodeDatasArr = $recodeDatas ? json_decode($recodeDatas, true) : [];
                if (count($recodeDatasArr) > 10)
                {
                    return show(config('code.error'), '请求异常，最多选择10个档案～');
                }
                $resData = [];
                $sexTxt = [
                    1 => '男',
                    2 => '女',
                ];
                $recodeModel = new Recode();
                $utilModel = new Util();
                foreach ($recodeDatasArr as $rid)
                {
                    $recode = $recodeModel->getInfoById($rid);
                    if (!$recode || $recode['uid'] != $this->user['id'])
                    {
                        return show(config('code.error'), '服务异常,档案信息异常～');
                    }
                    // 周岁
                    $age = Util::getAgeByBirth($recode['year'], $recode['month'], $recode['day'], 2);
                    $sex = $sexTxt[$recode['type']] ?? '未知';
                    $userDes = '日' . $utilModel->recodeAstroShorthand($recode['sun']) . '月' . $utilModel->recodeAstroShorthand($recode['moon']) . '升' . $utilModel->recodeAstroShorthand($recode['asc']);

                    $resData[] = [
                        'rid' => (int)$rid,
                        'name' => $recode['name'],
                        'avatar' => $recode['avatar'],
                        'comments' => $recode['comments'],
                        'user_des' => "{$sex}·{$age}周岁 {$userDes}",
                        'year' => $recode['year'],
                    ];
                }

                $updateData['recode_datas'] = $resData;
                break;
            case 2: //  2=>骰子
                $diceDatasArr = $diceDatas ? json_decode($diceDatas, true) : [];
                if (count($diceDatasArr) > 10)
                {
                    return show(config('code.error'), '请求异常，最多投10次结果～');
                }
                $resData = [];
                $planetArr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 16];// 行星id随机数种子
                foreach ($diceDatasArr as $diceData)
                {
                    if (!isset($diceData['planet'], $diceData['sign'], $diceData['house']))
                    {
                        return show(config('code.error'), '操作失败,骰子信息异常～');
                    }
                    if (!in_array($diceData['planet'], $planetArr, true) || $diceData['sign'] < 1 || $diceData['sign'] > 12 || $diceData['house'] < 1 || $diceData['house'] > 12)
                    {
                        return show(config('code.error'), '操作失败,骰子信息异常～');
                    }
                    $resData[] = $diceData;
                }
                $updateData['dice_datas'] = $resData;
                break;
            case 3: //  3=>塔罗
                $tarotDatasArr = $tarotDatas ? json_decode($tarotDatas, true) : [];
                if (count($tarotDatasArr) > 10)
                {
                    return show(config('code.error'), '请求异常，最多抽牌10轮～');
                }
                $resData = [];
                foreach ($tarotDatasArr as $tarotData)
                {
                    $resData1 = [];
                    foreach ($tarotData as $k => $tarotItem)
                    {
                        if ($tarotItem['card_id'] < 1 || $tarotItem['card_id'] > 78 || !in_array((int)$tarotItem['direction'], [1, 2], true))
                        {
                            return show(config('code.error'), '操作失败,更新信息异常～');
                        }
                        if (isset($tarotItem['index']))
                        {
                            $index = $tarotItem['index'];
                        } else
                        {
                            $index = $k + 1;
                        }
                        $resData1[] = [
                            'card_id' => $tarotItem['card_id'],
                            'direction' => $tarotItem['direction'],
                            'index' => $index,
                        ];
                    }

                    $resData[] = $resData1;
                }

                $updateData['tarot_datas'] = $resData;
                break;
        }

        $consultChatRtcRecordModel->saveNowRtcDataToCache(2, $this->appType2, $astrId, $updateData, true, $chatDetailId);

        // 向 咨询师 发送消息
        $consultDetailRefresh = [
            'target' => 'local',
            'link' => "alert_consult_question?id={$chatDetailId}&need_auth=2",
            'force_open' => 1,
        ];
        LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $astrId), LiveMessage::MSG_TYPE_POP_CONSULT_DETAIL_REFRESH, $consultDetailRefresh);

        return show(config('code.success'), '请求成功');
    }

    /**
     * 咨询评价
     * @return Json
     * @throws \Exception
     */
    public function comment()
    {
        $chatDetailId = input('id/d', 0);
        $tids = input('tids/s', '');
        $remark = input('remark/s', '');
        if (!$chatDetailId || !$tids)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (mb_strlen($remark) > 60)
        {
            return show(config('code.error'), '评价原因最多60字');
        }
        if ($remark)
        {
            $res = AliyunFilterWord::checkText($remark, 'article_comment');
            //若内容有违规且超过配置的相似比例，则进行隐藏不显示，将标签存入库中
            if ($res)
            {
                return show(0, '评价内容涉嫌' . $res['label']);
            }
        }

        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        $nowTimw = $this->request->time();
        $chatDetail = $consultChatRecordDetailsModel->getInfoById($chatDetailId);
        $rtcId = $chatDetail['extend']['rtc_data']['rtc_id'] ?? 0;
        if (!$chatDetail || $chatDetail['uid'] !== $this->user['id'] || !$rtcId)
        {
            return show(config('code.error'), '咨询信息不存在，评价失败～');
        }
        //个咨询只能评价一次
        $rtcInfo = $consultChatRtcRecordModel->getInfoById($rtcId);
        if (isset($rtcInfo['is_comment']) && $rtcInfo['is_comment'] > 0)
        {
            return show(config('code.error'), '已经评价过了，请勿重复操作～');
        }
        $tidsArr = explode(',', $tids);
        $tagInfoList = (new ZyhsTag())->batchGetInfoByIds($tidsArr);
        if (count($tagInfoList) != count($tidsArr))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $level = 0;
        foreach ($tagInfoList as $item)
        {
            if ($level === 0)
            {
                $level = $item['flag'];
            }
            if ($item['flag'] != $level)
            {
                return show(config('code.error'), '请求异常，请稍后再试～');
            }
        }
        if (in_array($level, [1, 5]) && empty($remark))
        {
            return show(config('code.error'), '评价原因不能为空');
        }
        if ($rtcInfo['status'] !== 4)
        {
            return show(config('code.error'), '咨询状态异常，评价失败');
        }
        // 写入 评价数据
        (new ZyhsConsultChatRtcRecordComment())->saveData([
            'rtc_id' => $rtcId,
            'app_type' => $this->appType2,
            'uid' => $this->user['id'],
            'astr_id' => $rtcInfo['astr_id'],
            'level' => $level,
            'tids' => $tids,
            'comment' => $remark,
            'comment_type' => 1,
            'create_time' => $nowTimw,
        ]);
        // 更新了评价状态
        $consultChatRtcRecordModel->updateData($rtcInfo['id'], $this->appType2, $rtcInfo['uid'], ['is_comment' => 1], 1);
        if ($level !== 3)
        {   // 记录 好评与差评
            $fields = $level > 3 ? 'level5_comment' : 'level1_comment';
            (new ZyhsConsultAstrData())->analysisDataUpdate($rtcInfo['astr_id'], (int)date('YmdH'), [
                $fields => Db::raw("{$fields} + 1"),
            ]);
        }
        // 向咨询师 发送信息
        $astrData = current($consultChatRecordDetailsModel->astrDataListResert([$chatDetail], [], $this->user, $this->appType2));
        $astrData['is_comment'] = 1;    // 已评价
        LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $rtcInfo['astr_id']), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
            'msg_type' => 2,
            'app_type' => $this->appType2,
            'uid' => $this->user['id'],
            'msg_data' => $astrData,
        ]);
        //  4星和5星处理 咨询师给用户回消息
        if ($level > 3)
        {
            $zlcr3ConsultChatRecordModel = new ZyhsConsultChatRecord();
            $chatId = $zlcr3ConsultChatRecordModel->getChatIdByAstrId($this->appType2, $this->user['id'], $rtcInfo['astr_id']);
            if (!$chatId)
            {
                $insertData = [
                    'app_type' => $this->appType2,
                    'uid' => $this->user['id'],
                    'astr_id' => $rtcInfo['astr_id'],
                    'last_chat_detail_id' => 0,
                    'last_chat_detail_time' => 0,
                    'create_time' => $nowTimw,
                ];
                // 创建新的会话
                $chatId = $zlcr3ConsultChatRecordModel->SaveData($insertData);
            }
            $consultMsgData = [
                'chat_id' => $chatId,
                'app_type' => $this->appType2,
                'uid' => $this->user['id'],
                'astr_id' => $rtcInfo['astr_id'],
                'type' => 1,    //  1=>APP消息 2=>用户发送消息
                'title' => '',
                'content' => '感谢你的评价及推荐！我会继续努力～', // 提问问题
                'data_type' => 1,   // 1=>普通消息  2=>图片  3=>语音咨询消息
                'extend' => [],  //  语音咨询消息 ｜ 图片信息
                'pid' => 0, // 待更新
                'create_time' => $nowTimw,
            ];
            $resData = $consultChatRecordDetailsModel->SaveData($chatId, $consultMsgData);
            $astrInfo = (new ZlcrAstr())->getInfoById($rtcInfo['astr_id']);
            $userData = current($consultChatRecordDetailsModel->userDataListResert([$resData], $astrInfo, $this->user, $this->appType2));
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_UID, 0, $this->user['id']), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                'msg_type' => 1,
                'astr_id' => $astrInfo['id'],
                'msg_data' => $userData,
            ]);
            $astrData2 = current($consultChatRecordDetailsModel->astrDataListResert([$resData], $astrInfo, $this->user, $this->appType2));
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $rtcInfo['astr_id']), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                'msg_type' => 2,
                'app_type' => $this->appType2,
                'uid' => $this->user['id'],
                'msg_data' => $astrData2,
            ]);
            // 更新用户端 最后咨询信息
            $zlcr3ConsultChatRecordModel->updateData($chatId, [
                'uid' => $this->user['id'],
                'last_chat_detail_id' => $chatDetailId,
                'last_chat_detail_time' => $nowTimw,
                'msg_num' => Db::raw('msg_num + 1'),
            ], $this->appType2);
            // 未读数 +1
            $zlcr3ConsultChatRecordModel->setUserUnreadChatIdMsgNum($this->appType2, $this->user['id'], $chatId, 1, 1);
        }
        // 更新 咨询师 能力分
        if ($level !== 3)
        {
            $commentLevelChangeScoreData = [
                1 => -20,
                2 => -10,
                3 => 0,
                4 => 3,
                5 => 5,
            ];
            $zlcr3ConsultAccountModel = new Zlcr3ConsultAccount();
            $consultAccountInfo = $zlcr3ConsultAccountModel->getInfoById($rtcInfo['astr_id']);
            // 更新能力分
            $zlcr3ConsultAccountModel->changeAstrLevelScore($consultAccountInfo, $rtcId, 1, $commentLevelChangeScoreData[$level], 1);
        }
        return show(config('code.success'), '请求成功');
    }

    /**
     * 连线咨询 推荐占星师
     * @return Json
     * @throws \Exception
     */
    public function recommend()
    {
        $chatDetailId = input('id/d', 0);
        $type = input('type/d', 0);

        if (!$chatDetailId || !in_array($type, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();

        $chatDetail = $consultChatRecordDetailsModel->getInfoById($chatDetailId);
        $rtcId = $chatDetail['extend']['rtc_data']['rtc_id'] ?? 0;
        if (!$chatDetail || $chatDetail['uid'] !== $this->user['id'] || !$rtcId)
        {
            return show(config('code.error'), '咨询信息不存在，推荐失败～');
        }
        $rtcInfo = $consultChatRtcRecordModel->getInfoById($rtcId);
        if ($rtcInfo['status'] !== 4)
        {
            return show(config('code.error'), '咨询状态异常，推荐失败～');
        }
        if ($rtcInfo['is_recommend'] === 1)
        {
            return show(config('code.success'), '操作成功');
        }

        // 更新了评价状态
        $consultChatRtcRecordModel->updateData($rtcInfo['id'], $this->appType2, $rtcInfo['uid'], ['is_recommend' => $type], 1);

        if ($type === 1)
        {   // 推荐
            $zlcr3ConsultAccountModel = new Zlcr3ConsultAccount();
            $consultAccountInfo = $zlcr3ConsultAccountModel->getInfoById($rtcInfo['astr_id']);
            $zlcr3ConsultAccountModel->changeAstrLevelScore($consultAccountInfo, $rtcId, 1, 2, 6);

            (new ZyhsConsultAstrData())->analysisDataUpdate($rtcInfo['astr_id'], (int)date('YmdH'), [
                'recommend_num' => Db::raw('recommend_num + 1'),
            ]);
        }

        return show(config('code.success'), '操作成功');
    }

    /**
     * 咨询详情
     * @return Json
     * @throws \Exception
     */
    public function rtcChatDetail()
    {
        $chatDetailId = input('id/d', 0);
        $type = input('type/d', 0);//1=>完整 2=>精简【弹窗评价页面进入】
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();

        $chatDetail = $consultChatRecordDetailsModel->getInfoById($chatDetailId);
        $rtcId = $chatDetail['extend']['rtc_data']['rtc_id'] ?? 0;
        if (!$chatDetail || $chatDetail['uid'] !== $this->user['id'] || !$rtcId)
        {
            return show(config('code.error'), '服务异常，咨询信息不存在～');
        }
        $data = (new ZyhsConsultChatRtcRecord())->getInfoById($rtcId);

        $astrInfos = (new ZlcrAstr())->getInfoById($data['astr_id'], ['nickname', 'avatar']);

        $couponInfoData = null;
        if (isset($data['extend']['cid']))
        {
            $userCouponAttr = (new UserCoupon())->getInfoById($data['extend']['cid']);
            $desc = "免费{$userCouponAttr['discount']}分钟（优惠券）";
            if ($userCouponAttr['condition'] > 0)
            {
                $desc = "满{$userCouponAttr['condition']}分钟，" . $desc;
            }
            $couponInfoData = [
                'title' => '优惠',
                'des' => $desc,
                'type' => 1,
            ];
        }
        // 连线福利【新人福利】
        $rtcBenefits = null;
        if (isset($data['extend']['free_rtc_duration']) && $data['extend']['free_rtc_duration'] > $data['test_duration'])
        {   // 连线福利
            $rtcBenefits = [
                'title' => '连线福利',
                'des' => sprintf("免费%d分钟", (int)($data['extend']['free_rtc_duration'] / 60)),
                'type' => 1,
            ];
        }

        if ($type === 1)
        {
            $comment = $data['is_comment'] ? (new ZyhsConsultChatRtcRecordComment())->getInfoById($data['id'], ['level']) : null;

            $res = [
                'title' => '本次消耗详情',
                'list' => [
                    [
                        'title' => '服务编号',
                        'des' => $data['chat_detail_id'] ?? 0,
                        'type' => 2,
                    ],
                    [
                        'title' => '申请时间',
                        'des' => date('Y-m-d H:i:s', $data['create_time']),
                        'type' => 1,
                    ],
                    [
                        'title' => '咨询师',
                        'des' => $astrInfos['nickname'],
                        'type' => 1,
                    ],
                    [
                        'title' => '咨询师单价',
                        'des' => $data['unit_price'] . '准币/分钟',
                        'type' => 1,
                    ],
                    [
                        'title' => '连线时长',
                        'des' => gmdate("H:i:s", $data['duration']),
                        'type' => 1,
                    ],
                ],
            ];
            if ($couponInfoData)
            {   // 优惠券信息
                $res['list'][] = $couponInfoData;
            }
            if ($rtcBenefits)
            {   // 连线福利
                $res['list'][] = $rtcBenefits;
            }
            $res['list'][] = [
                'title' => '计费时长',
                'des' => ceil($data['eff_duration'] / 60) . '分钟',
                'type' => 1,
            ];
            $res['list'][] = [
                'title' => '连线消耗',
                'des' => $data['coin'] . '准币',
                'type' => 1,
            ];
            if ($data['status'] === 4)
            {   // 正常挂断
                $res['list'][] = [
                    'title' => '评价',
                    'des' => $data['is_comment'] ? $comment['level'] : '前往评价',
                    'type' => $data['is_comment'] ? 3 : 4,
                ];
                if ($data['is_recommend'] === 1)
                {
                    $res['list'][] = [
                        'title' => '推荐',
                        'des' => '已推荐',
                        'type' => 1,
                    ];
                }
            }
        } else
        {
            $res = [
                'title' => '本次消耗详情',
                'list' => [
                    [
                        'title' => '服务编号',
                        'des' => $data['chat_detail_id'] ?? 0,
                        'type' => 2,
                    ],
                    [
                        'title' => '咨询师单价',
                        'des' => $data['unit_price'] . '准币/分钟',
                        'type' => 1,
                    ],
                    [
                        'title' => '连线时长',
                        'des' => gmdate("H:i:s", $data['duration']),
                        'type' => 1,
                    ],
                ],
            ];
            if ($couponInfoData)
            {
                $res['list'][] = $couponInfoData;
            }
            if ($rtcBenefits)
            {   // 连线福利
                $res['list'][] = $rtcBenefits;
            }
            $res['list'][] = [
                'title' => '计费时长',
                'des' => ceil($data['eff_duration'] / 60) . '分钟',
                'type' => 1,
            ];
            $res['list'][] = [
                'title' => '连线消耗',
                'des' => $data['coin'] . '准币',
                'type' => 1,
            ];
        }
        $res['nickname'] = $astrInfos['nickname'];
        $res['avatar'] = $astrInfos['avatar'];

        return show(config('code.success'), '请求成功', $res);
    }

    /**
     * 我的咨询列表
     * @return Json
     * @throws \Exception
     */
    public function rtcChatList()
    {
        $data = $this->user ? (new ZyhsConsultChatRtcRecord())->userRtcChat($this->appType2, $this->user['id']) : [];

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 举报占星师
     * @return Json
     * @throws \Exception
     */
    public function reportAstr()
    {
        $astrId = input('astr_id/d', 0);
        $feedback = input('feedback/s', '');
        $tel = input('phone/s', '');
        if (!$feedback || mb_strlen($feedback) > 60)
        {
            return show(config('code.error'), '举报内容字数60字以内');
        }
        $astrInfo = (new ZlcrAstr())->getInfoById($astrId, ['nickname']);
        if (!$astrInfo)
        {
            return show(config('code.error'), '咨询师不存在');
        }
        (new Zlcr3ConsultAccountReport())->insert([
            'app_type' => 2,    // 1=>准有好事 2=>准了APP
            'uid' => $this->user['id'],
            'astr_id' => $astrId,
            'tel' => $tel,
            'content' => $feedback,
            'create_time' => time(),
        ]);
        return show(config('code.success'), '举报成功');
    }

    /**
     * 咨询消息已读
     * @return Json
     * @throws \Exception
     */
    public function consultChatMsgRead()
    {
        $astrId = input('astr_id/d', 0);
        if (!$astrId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $consultChatIdModel = new ZyhsConsultChatRecord();
        $chatId = $consultChatIdModel->getChatIdByAstrId($this->appType2, $this->user['id'], $astrId);
        if ($chatId)
        {
            $consultChatIdModel->updateData($chatId, ['msg_num' => 0], $this->appType2);
            $consultChatIdModel->setUserUnreadChatIdMsgNum($this->appType2, $this->user['id'], $chatId, 2, 0);
        }

        return show(config('code.success'), '请求成功');
    }

    /**
     * 关注取消关注
     * @return \think\response\Json
     * @throws \Exception
     */
    public function follow()
    {
        $type = input('type/d', 0);
        $astrId = input('astr_id/d', 0);

        $astrInfo = (new ZlcrAstr())->getInfoById($astrId, ['tel']);
        if (!$astrInfo)
        {
            return show(config('code.success'), 'Success.');
        }
        $followModel = new Zlcr3Follow();
        $followIdsPageData = $followModel->userFollowInfo($this->user['id'], -1);
        $followIds = array_keys($followIdsPageData['data']);
        //关注
        if ($type === 1)
        {
            if (in_array($astrId, $followIds, true))
            {
                return show(config('code.success'), '关注成功');
            }

            $followModel->SaveData([
                'type' => 1,
                'uid' => $this->user['id'],
                'astr_id' => $astrId,
                'create_time' => $this->request->time(),
            ]);
        }//取消关注
        else
        {
            if (!in_array($astrId, $followIds, true))
            {
                return show(config('code.success'), '取消关注成功');
            }

            $followModel->delData($this->user['id'], $astrId);
        }

        return show(config('code.success'), 'Success.');
    }

    /**
     * 咨询师关注列表
     * @return Json
     * @throws \Exception
     */
    public function astrFollowList()
    {
        $page = input('page/d', 1);
        $zlcrAstrModel = new ZlcrAstr();
        $zlcr3ConsultAccountModel = new Zlcr3ConsultAccount();

        if (Util::ZyhsIsHuaweiOrHonorOrOppoHg(2))
        {
            $rtcConfig = (new ZyhsConfig())->configInfo('rtc');
            if (Util::IsHuaweiAndOppo())
            {
                if (isset($rtcConfig['huawei_work_intro']) && $rtcConfig['huawei_work_intro'])
                {
                    $workIntro = $rtcConfig['huawei_work_intro'];
                }
            } else
            {
                if (isset($rtcConfig['honor_work_intro']) && $rtcConfig['honor_work_intro'])
                {
                    $workIntro = $rtcConfig['honor_work_intro'];
                }
            }
        }
        if ($this->user)
        {
            $resData = (new Zlcr3Follow())->userFollowInfo($this->user['id'], $page);
            // 获取新人福利 免充值 发起连线
            $newUserWelfare = (new ZyhsConsultRtcUserBenefits())->getConsultRtcUserBenefits($this->appType2, $this->user['id']);
            $freeRtcDuration = $newUserWelfare ? (($newUserWelfare['min'] ?? 0) * 60) : 0;
            // 免费 连线 时长
            $freeConsultDuration = $freeRtcDuration > 0 ? 1 : 0;
            if ($freeConsultDuration > 0)
            {
                $consultBtnName = sprintf("免费咨询%d分钟", (int)($freeRtcDuration / 60));
            } else
            {
                $consultBtnName = '连线咨询';
            }
            $astroList = [];
            foreach ($resData['data'] as $astrId => $fid)
            {
                $astrInfo = $zlcrAstrModel->getInfoById($astrId);
                $consultAstrInfo = $zlcr3ConsultAccountModel->getInfoById($astrId);
                if ($consultAstrInfo['consult_status'] != 1)
                {
                    continue;
                }
                $des = $workIntro ?? ($astrInfo['extend']['work_intro'] ?? '');
                $tips = "";
                if ($consultAstrInfo['service_duration'])
                {
                    $i = ceil($consultAstrInfo['service_duration'] / 60);
                    $tips .= '服务' . ($i > 200 ? '200+' : $i) . '分钟';
                }
                if ($consultAstrInfo['recommended_nums'])
                {
                    if ($tips)
                    {
                        $tips .= '·';
                    }
                    $tips .= $consultAstrInfo['recommended_nums'] . "次被推荐";
                }

                $tagIcons = [];
                if ($consultAstrInfo['tids'])
                {
                    $tagIcons = $zlcr3ConsultAccountModel->getTagsIcon($consultAstrInfo['tids']);
                }
                $tags = [];
                if ($consultAstrInfo['tags'])
                {
                    $tags = $zlcr3ConsultAccountModel->getTags($consultAstrInfo['tags']);
                    if (Util::ZyhsIsHuaweiOrHonorOrOppoHg(2))
                    {
                        $tags = array_values(array_diff($tags, ['星盘']));
                    }
                }

                $status = $consultAstrInfo['status'] === 1 ? 1 : 2;
                if ($status === 1)
                {
                    $btnData = [['title' => '预沟通', 'type' => 1,], ['title' => $consultBtnName, 'type' => 2,],];
                } else
                {
                    $btnData = [['title' => '预沟通', 'type' => 1,],];
                }

                $astroList[] = [
                    'name' => $astrInfo['nickname'],
                    'avatar' => $astrInfo['avatar'],
                    'tags_icon' => $tagIcons,
                    'tags' => $tags,
                    'des' => $des,
                    'status' => $status,
                    'id' => $astrId,
                    'tips' => $tips,
                    'level' => $consultAstrInfo['level'],
                    'btn_data' => $btnData,
                ];
            }
            $resData['data'] = $astroList;
            $newUserWelfare = (new ZyhsConsultRtcUserBenefits())->getConsultRtcUserBenefits($this->appType2, $this->user['id']);
            $freeRtcDuration = $newUserWelfare ? (($newUserWelfare['min'] ?? 0) * 60) : 0;
            $resData['free_consult'] = $freeRtcDuration > 0 ? 1 : 0;
        } else
        {
            $resData = [];
        }
        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 获取 故障挂断 原因
     * @return Json
     */
    public function getCancelReason()
    {
        $data = [
            [
                'id' => 1,
                'name' => '听不见主播声音',
            ], [
                'id' => 2,
                'name' => '主播听不见我的声音',
            ],
            [
                'id' => 3,
                'name' => '主播有杂音',
            ],
            [
                'id' => 4,
                'name' => '我的麦有杂音',
            ],
        ];

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 获取评价标签
     * @return Json
     * @throws \Exception
     */
    public function getCommentTag()
    {
        $tagModel = new ZyhsTag();
        $tag = $tagModel->getLevelTag(1, 0);
        $tag = $tagModel->getQuestionAllsResrt($tag);

        return show(config('code.success'), '请求成功', $tag);
    }
}
